import axios from 'axios'
import { HOST } from './config'
import router from '../router/index'

const instance = axios.create({
    baseURL: HOST
})

// token过期  重定向 login
function setStatus (i) {
    console.log('token过期  重定向 login')
    router.push('/login')
}

// 统一处理返回数据
function resData ({ res, resolve, reject }) {
    if (res.data.code === 401) { // token过期 或 没有token
        setStatus(res)
        return
    } else if (res.data.code === 200) { // 正常
        resolve(res)
        return
    }
    // Element.Message.error(res.data.msg)
    reject()
}

function request (url, params, options) {
    return new Promise((resolve, reject) => {
        function axiosRequest () {
            instance({
                url: url,
                method: params.method,
                headers: params.header,
                data: params.method === 'POST' || params.method === 'PUT' ? params.body : null,
                params: params.method === 'GET' || params.method === 'DELETE' ? params.body : null
            }).then(res => {
                resData({ res, resolve, reject })
            }).catch(err => {
                console.log(err)
                reject(err)
            })
        }
        if (options.noToken || params.header.Authorization) { // 不验证token || 参数里有token
            axiosRequest()
        } else {
            if (localStorage.getItem('superToken')) {
                params.header.Authorization = 'Bearer ' + localStorage.getItem('superToken')
                axiosRequest()
            } else {
                console.log('无token 重定向 login')
                router.push('/login')
            }
        }
    })
}

var fetch = {
    get: function (url, params = {}, options = {}) {
        return request(url, {
            method: 'GET',
            header: {},
            body: {},
            ...params
        }, options)
    },
    post: function (url, params = {}, options = {}) {
        return request(url, {
            method: 'POST',
            header: {},
            body: {},
            ...params
        }, options)
    }
}

export default fetch
